const db = require('../database')

module.exports = {
  // 新建标签
  addTag(name) {
    const model = new db.Tag({name, blog: []})
    return model.save()
  },
  // 根据id查找标签
  async getTagById(_id, page=1) {
    const limit = 2
    const skip = limit*(page-1)
    const tag = await db
      .Tag
      .where({_id})
      .populate({
        path:'blog',
        select:'title _id href',
        match: {
          isPublished: true
        },  
        options:{limit, skip}
      })
      .findOne()
    const blogCount = (await db
      .Tag
      .where({_id})
      .populate({
        path:'blog',
        match: {
          isPublished: true
        }
      }).findOne()).blog.length
      return {tag, blogCount}
  },
  // 根据开头查找标签
  findTagByStart(start) {
    return db
      .Tag
      .where({
        name: new RegExp(`^${start}`, 'mi')
      })
      .select('_id name')
      .exec()
  },
  // 获取全部标签
  getAllTag(){
    return db.Tag.find()
  }
}